package com.goldmantis.activemq.ch3.queue;

import java.util.Date;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageProducer;
import javax.jms.Queue;
import javax.jms.Session;

import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.ActiveMQSession;

public class MQQueueSessionPublisher {

    private static String brokerURL = "tcp://localhost:31616";
    private static transient ConnectionFactory factory;
    private transient Connection connection;
    private transient ActiveMQSession session;
    private transient MessageProducer producer;
    private transient Queue destination;
    
    private static int count = 10;
    private static int total;
    private static int id = 1000000;
    
    private String jobs[] = new String[]{"suspend", "delete"};
    
    public MQQueueSessionPublisher() throws JMSException {
    	factory = new ActiveMQConnectionFactory(brokerURL);
    	connection = factory.createConnection();
    	//connection.setClientID("clientID");
        connection.start();
        session = (ActiveMQSession)connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        destination = session.createQueue("JOBS.1");
        producer = session.createSender(destination);
        //producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
        //producer.setTimeToLive(5000);
    }    
    
    public void close() throws JMSException {
        if (connection != null) {
            connection.close();
        }
    }    
    
	public static void main(String[] args) throws JMSException {
    	MQQueueSessionPublisher publisher = new MQQueueSessionPublisher();
    	publisher.sendMessage();
        while (total < 1000) {
        	publisher.sendMessage();
            total ++;
            System.out.println("Published '"+total + "' job messages");
            try {
              Thread.sleep(100);
            } catch (InterruptedException x) {
            }
          }
        publisher.close();

	}
	
    public void sendMessage() throws JMSException {
        Message message = session.createTextMessage(String.format("%d",id++));
        Date date = new Date();
        message.setJMSExpiration(date.getTime()+5000);
        //System.out.println("Sending: id: " + ((ObjectMessage)message).getObject() + " on queue: " + destination);
        producer.send(destination, message);
    }	

}
